<script setup>
import { ref, reactive, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted,getCurrentInstance,watch} from "vue"
import { tranListToTreeData } from '@/hooks/index'
import { getPermissionList,deletePermission } from '@/api/System/index'
import EditDialog from './Components/EditDialog.vue'
import { useImportImg } from '@/hooks/index'
const btnAddBlue = useImportImg('btn-add-blue')
// ============弹框部分逻辑start=========
const dialogShow = ref(false)
const permissionId = ref('')
const addOrEdit = ref(true)
const editForm = ref({})
const dialogClose = () => {
    dialogShow.value = false
}

const dialogSure = () => {
    dialogShow.value = false
    getMenuList(menuitem.value)
}
const permissionLoading = ref(false)

const fName = ref('')



// ==============搜索部分start=======
const menuOPtions = ref([
    {
        value: 1,
        label: '管理平台',
    },
    {
        value: 2,
        label: '商户SAAS',
    },
    {
        value: 3,
        label: 'C端客户',
    },
])

const menuitem = ref(1)

const filterNode = (value, data) => {
  if (!value) return true
  return data.permissionLabel.includes(value)
}
const filterText = ref('')

watch(filterText, (val) => {
    console.log(val,'val');
    // console.log(treeNode.value,'treeNode.value');
    treeNode.value.filter(val)
})


// ==============搜索部分end=========


// ============弹框部分逻辑end=========

const handleNodeClick = (data,node) => {
    // console.log(data,'data');
}


const defaultProps = {
  children: 'children',
  label: 'permissionLabel',
}

const treeData = ref([])


const getMenuList = async(type = 1) => {
    try {
        permissionLoading.value = true
        let data = {
            page:{
                size:20,
                current:1
            },
            permissionClient:type
        }
       const res = await getPermissionList(data)
       treeData.value = tranListToTreeData(res,'0')
       console.log(treeData,'res');
    } catch (error) {
        
    }finally{
        permissionLoading.value = false
    }
}


const search = () => {
    getMenuList(menuitem.value) 
}


const filterMenuTYpe = (val) => {
    let type = ''
    switch (val) {
        case 'M':
            type = '目录'
            break;
        case 'C':
            type = '菜单'
            break;
        case 'B':
            type = '按钮'
            break;
        case 'F':
            type = '字段'
            break;    
        default:
            break;
    }
    return type
}


// ===========展开折叠逻辑start==============
const instance = getCurrentInstance();

const treeNode = ref(null)
// const isExpand = ref(false)
const expandTree = (node) => {
      node.expanded = !node.expanded;
}
// ===========展开折叠逻辑end================

// =============新增逻辑start==============
const addMenu = (node,data) => {
    console.log(node,data,'新增')
    permissionId.value = data.id
    fName.value = data.permissionLabel || ''
    addOrEdit.value = true
    dialogShow.value = true

}

const addTop = () => {
    dialogShow.value = true
    permissionId.value = '0'
    fName.value = 'TOP'
    addOrEdit.value = true
}
// =============新增逻辑end==============


// ============编辑逻辑start============
const editMenu = (node,data) => {
    console.log(data,'编辑');
    editForm.value = {
        id:data.id || '',
        permissionName:data.permissionName, //权限名称
        permissionLabel:data.permissionLabel, //权限标签
        parentId:data.parentId || '', //父节点id
        orderNum:data.orderNum || '', //显示顺序
        redirect:data.redirect || '', //重定向地址
        path:data.path || '', //路由地址
        component:data.component || '', //组件路径
        isFrame:data.isFrame, //是否外链
        permissionType:data.permissionType, //权限类型 M目录 C菜单 B按钮 F字段）
        visible:data.visible, //是否可见
        permissionStatus:data.permissionStatus, //权限状态
        icon:data.icon || '', //图标路径
        permissionRemark:data.permissionRemark || '', //权限备注
        permissionClient:data.permissionClient || 1, //使用端口1: 管理平台 2: 商户SAAS 3: C端客户(默认1)
        }
    fName.value = data.permissionLabel || '',
    dialogShow.value = true
    permissionId.value = data.id
    addOrEdit.value = false
}

// ============编辑逻辑end==============


// ============删除逻辑start============
const deleteMenu = (node,data) => {
    console.log(node,data,'删除');
    ElMessageBox(
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error',
                    title: '提示',
                    showCancelButton: true,
                    confirmButtonClass: 'delete',
                    message:`确定删除该${filterMenuTYpe(data.permissionType)}`,
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = 'Loading...'
                            try {
                                let obj = {
                                    sysPermissionId: Number(data.id)
                                }
                              const res = await deletePermission(obj)
                              ElMessage.success('删除成功');
                             
                            } catch (error) {
                              
                            }finally{
                                getMenuList(menuitem.value)
                              instance.confirmButtonLoading = false
                              done()
                            }
                          
                        } else {
                            done()
                        }
                    },
                }
            )
}
// ============删除逻辑end==============
getMenuList()
//组件挂载到节点上之前执行的函数
onBeforeMount(()=>{})

//组件挂载完成后执行的函数
onMounted(()=>{})

//组件更新之前执行的函数
onBeforeUpdate(()=>{})

//组件更新完成之后执行的函数
onUpdated(()=>{})

//组件卸载之前执行的函数
onBeforeUnmount(()=>{})

//组件卸载完成后执行的函数
onUnmounted(()=>{})

</script>

<template>
  <div class="container" v-loading="permissionLoading">
    <div class="search-header">
        
        <el-select
            v-model="menuitem"
            class="m-2"
            placeholder="请选择系统"
            style="width: 240px"
        >
            <el-option
            v-for="item in menuOPtions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>

        <el-input style="width: 300px; margin-left: 50px; margin-right: 15px;" v-model.trim="filterText" placeholder="请输入筛选的名称" />

        <el-button type="success" @click="search">搜索</el-button>
    </div>
    <div class="add-top">
        <el-button style="margin-bottom: 8px;" type="primary" plain @click="addTop">
                    <el-image :src="btnAddBlue" class="btnIcon" />
                    新增目录
        </el-button>
    </div>
    <div class="header">
        <el-row type="flex" justify="space-between" align="middle">
            <el-col :span="5">
                <div class="menu-name">菜单名称</div>
            </el-col>
            <el-col :span="5">
                <div class="menu-name">菜单类型</div>
            </el-col>
            <el-col :span="5">
                <div class="menu-name">显示状态</div>
            </el-col>
            <el-col :span="5">
                <div class="menu-name">权限标识</div>
            </el-col>
            <el-col :span="4">
                <div class="menu-name action">操作</div>
            </el-col>
        </el-row> 
    </div>
    <el-tree 
    :data="treeData" 
    :props="defaultProps" 
    @node-click="handleNodeClick" 
    :expand-on-click-node="false"
    ref="treeNode"
    :filter-node-method="filterNode"
    >
        <template #default="{ node, data }">
            <el-row type="flex" justify="space-between" align="middle" style="height: 40px; width: 100%;">
                <el-col :span="5">
                <div class="menu-name" @click="expandTree(node)">{{ node.label }}</div>
                </el-col>
                <el-col :span="5">
                <div>{{ filterMenuTYpe(data.permissionType) }}</div>
                </el-col>
                <el-col :span="5">
                <div v-if="data.visible">
                    <el-tag type="success">是</el-tag>
                </div>
                <div v-else>
                    <el-tag type="danger">否</el-tag>
                </div>
                </el-col>
                <el-col :span="5">
                    <div>{{data.perms}}</div>
                </el-col>
                <el-col :span="4">
                    <div>
                        <el-button size="small"  plain type="success" @click="addMenu(node,data)">新增</el-button>
                        <el-button size="small"  plain type="primary" @click="editMenu(node,data)">编辑</el-button>
                        <el-button size="small"  plain type="danger" @click="deleteMenu(node, data)">删除</el-button>
                    </div>
                </el-col>
            </el-row>
      </template>
    </el-tree>
    <edit-dialog 
    v-if="dialogShow"
    :dialogFormVisible="dialogShow"
    :permissionId="permissionId"
    :addOrEdit="addOrEdit"
    :editForm="editForm"
    :Client="menuitem"
    :fName="fName"
    @close="dialogClose"
    @sure="dialogSure"
    ></edit-dialog>
  </div>
</template>

<style lang="less" scoped>
.container{
    width: 100%;
    height: 100%;
    padding: 25px 50px;
    box-sizing: border-box;
    // .el-tree-node__content{
    //     padding: 20px;
    // }
    :deep(.el-tree-node){
        padding: 8px;
    }
    .menu-name{
        color: #000000;
        font-family: "PingFang SC";
        font-size: 14rpx;
        font-style: normal;
        font-weight: 600;
        line-height: 14rpx;
    }
    .action{
        margin-left: 60px;
    }
    .header{
        margin-bottom: 20px;

    }
    .el-tree{
        min-height: calc(100vh - 236px);
    }
    .search-header{
        display: flex;
        margin-bottom: 16px;
    }
}

</style>
